import re

from common.utils.file_util import CacheUtil
from common.utils.random_util import RandomUtil
from common.utils.string_util import StringUtil
from common.variables import global_variables, env_variables


def deal_params(params, *, cache_key=None):
    for k, v in params.items():
        if not isinstance(v, str):
            continue
        # {[]}全局变量
        pattern_global = re.compile(r'^\{\[(.*)\]\}$')
        # {{}}环境变量
        pattern_env = re.compile(r'^\{\{(.*)\}\}$')
        # {{}}随机变量
        pattern_random = re.compile(r'^\[\[(.*)\]\]$')
        # 缓存变量
        pattern_cache = re.compile(r'^\${(.*)}$')

        match_global = re.match(pattern_global, v)
        match_env = re.match(pattern_env, v)
        match_random = re.match(pattern_random, v)
        match_cache = re.match(pattern_cache, v)
        if match_global:
            key = match_global.groups()[0]
            params[k] = global_variables.global_vars[key]
        elif match_env:
            key = match_env.groups()[0]
            params[k] = env_variables.get_variables(key)
        elif match_random:
            ori_param = match_random.groups()[0]
            params[k] = ori_param + '(' + RandomUtil.get_timestamp() + ')'
        elif match_cache:
            if cache_key:
                # 获取${}中间的变量名，并根据变量名找到cache中的变量值进行替换
                variable = match_cache.groups()[0]
                cache = CacheUtil.result[cache_key]
                params[k] = cache[variable]


if __name__ == '__main__':
    params = '{{123}}'
    pattern_env = re.compile(r'^\{\{(.*)\}\}$')
    match_env = re.match(pattern_env, params)
    print(match_env.groups()[0])